package git.luohao.config;

import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.csp.sentinel.datasource.*;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import git.luohao.datasource.DBRefreshableDatasource;
import git.luohao.datasource.DBWritableDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Configuration
@ConditionalOnClass({DataSource.class})
public class DatabaseRuleConfiguration {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @PostConstruct
    public void dbRefreshableDataSource() {
        ReadableDataSource<String, List<FlowRule>> ds = new DBRefreshableDatasource<>(
                jdbcTemplate, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}), 10000L
        );
        FlowRuleManager.register2Property(ds.getProperty());

        DBWritableDataSource<List<FlowRule>> wds = new DBWritableDataSource<>(jdbcTemplate, this::encodeJson);
        WritableDataSourceRegistry.registerFlowDataSource(wds);
    }

    private <T> String encodeJson(T t) {
        return JSON.toJSONString(t);
    }
}